package sto.orz.html.form;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import sto.orz.commons.DotStringUtils;
import sto.orz.commons.ResourceUtils;
import sto.orz.html.Element;
import sto.orz.html.ElementType;
import sto.orz.html.Select;

public class FormBuilder {
	public Form getForm(String pid, Class clazz) {
		Assert.notNull(clazz.getAnnotation(sto.orz.html.Form.class));

		Form form = new Form(pid);
		//form.setAction(sto.orz.commons.Convention.getFormAction(pid)); // getAction());
		form.setAction("/api/save.do");
		form.setElements(this.getFormElements(pid, clazz));

		return form;
	}

	public List<FormElement> getFormElements(String pid, Class clazz) {
		List<FormElement> elements = new ArrayList<FormElement>();

		Field[] fields = clazz.getDeclaredFields();
		for (java.lang.reflect.Field field : fields) {
			elements.addAll(this.getFormElements(pid, field));
		}
		return elements;
	}

	public List<FormElement> getFormElements(String pid, Field field) {
		// ElementConfig的存在只是为了得到默认element配置
		ElementConfig el;
		try {
			el = new ElementConfig(field.getAnnotation(Element.class));
		} catch (NullPointerException e) {
			el = new ElementConfig();
		}

		return getFormElements(pid, field, el);
	}

	private List<FormElement> getFormElements(String pid, Field field,
			ElementConfig a) {
		List<FormElement> elements = new ArrayList<FormElement>();
		FormElement formElement = new FormElement();

		String eid = (StringUtils.isNotBlank(a.getMapping())) ? a.getMapping()
				: field.getName();
		String name = field.getName();

		String caption = a.getLabel();
		if (StringUtils.isBlank(caption))
			caption = ResourceUtils.getStringOrNull(name);
		if (StringUtils.isBlank(caption))
			caption = name;

		// if (DataTypeUtils.isBasicDataType(field.getType())) {
		if (a.getExtendMode() == ExtendMode.NONE) {
			// 为selectbox组装数据
			if (a.getElementType() == ElementType.SELECTBOX) {
				Select sb = field.getAnnotation(Select.class);
				Object[] raw = new Object[] { "select ", a.getMapping(), ",",
						sb.display(), " from ", field.getType().getName(),
						" as ", name };

				String hql = StringUtils.join(raw);
				formElement.setValue(hql);
			}

			formElement.setName(DotStringUtils.addRoot(eid, pid));
			formElement.setLabel(caption);
			formElement.setType(a.getElementType());

			elements.add(formElement);
		} else {
			if (a.getExtendMode() == ExtendMode.INCLUDE) {
				elements.addAll(this.getFormElements(eid, field.getType()));
			}
		}
		return elements;
	}
}
